import { defineStore } from 'pinia'
import {
  accountLoginRequest,
  getUserInfoById
} from '@/service/login/login'
import { localCache } from '@/utils/cache'
import router from '@/router'
import { LOGIN_TOKEN_KEY } from '@/global/constants'

const useLoginStore = defineStore('login', {
  state: () => ({
    token: '',
    userInfo: {}
  }),
  actions: {
    async loginAccountRequest(account) {
      // 1.登录账号，获取token等信息
      const loginResult = await accountLoginRequest(account)
      console.log('loginResult: ', loginResult)
      if (loginResult.code === 0) {
        const id = loginResult.data.id
        const name = loginResult.data.account

        this.token = loginResult.data.token

        // 2.缓存token
        localCache.setCache(LOGIN_TOKEN_KEY, this.token)

        // 3.请求登录用户详细信息(role信息)
        const userInfoResult = await getUserInfoById(id)
        this.userInfo = userInfoResult.data

        // 4.根据角色请求用户权限(菜单)


        localCache.setCache('userInfo', this.userInfo)

        // 跳转main页面
        router.push('/main')
        return loginResult
      } else {
        console.log('登录失败')
        return loginResult
      }
    },
    loadLocalCacheAction() {
      const token = localCache.getCache(LOGIN_TOKEN_KEY)
      const userInfo = localCache.getCache('userInfo')
      if (token && userInfo) {
        this.token = token
        this.userInfo = userInfo
      }
    }
  }
})

export default useLoginStore